<?php
	/*
		PandaForum: PHP Forum Engine
		
		Jesse Gill, 0108377707
	*/
	
	require_once('./src/classes/DBConnection.php');
	require_once('./src/functions/rand.php');
	require('./src/config.php');
	
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-store, no-cache, must-revalidate");
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache");
	
	$connection = new DBConnection();
	$connection->connect($host, $username, $password, $dbname);
	
	if (! $connection->is_connected())
	{
		die($connection->get_error());
	}
	
	// $_POST data
	$username =					$connection->clean_var($_GET['username']);
	$password =					$connection->clean_var($_GET['password']);
	
	$row = $connection->get_result_array("SELECT id FROM user WHERE username='$username' AND password=SHA('$password')");
	
	$loggingin = true;
	$failedreason = "";
	
	if (!empty($row))
	{
		$id = $row['id'];
		$sid = generateRandomString(64);
		
		if ($connection->query_noresult("UPDATE user SET sid='$sid', lastactive=NOW(), lastlogin=NOW() WHERE id='$id'") != 0)
		{
			setcookie('id', $row['id'], 0, "/");
			setcookie('sid', $sid, 0, "/");
			setcookie('sn', $username, 0, "/");
		}
		else
		{
			$loggingin = false;
			$failedreason = "Failed to set session id.";
		}
	}
	else
	{
		$loggingin = false;
		$failedreason = "Invalid username/password.";
	}
	
	require_once('./src/classes/Structure.php');
	
	$structure = new Structure('');
	
	if ($loggingin)
	{
		$structure->print_usermenu_box($username);
	}
	else
	{
		$structure->print_login_box();
		echo "$failedreason";
	}
	
	$connection->close();
?>
